package com.shanks.home.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;

/**
 * @author Shanks
 * @time 2014.01.08
 */
public class SocketCommandHeader {
	// 包头大小
	public final static int HEADER_SIZE = 8;

	//字段定义
	public final static class Enum_Command_Header {
		public final static byte Flag		= 1;	// string	2
		public final static byte Cmd		= 2;	// unsigned_short	2
		public final static byte Version 	= 3;	// unsigned_short	2
		public final static byte BodyLength = 4;	// unsigned_short	2
	}
		
	/***********组包函数*****************
	 * byte[] encode(ByteHashMap hashBody)
	 * 入口参数：ByteHashMap hashBody	//组包参数
	 * 返回参数：byte[]					//组包数据 
	 ***********************************/	
	public static byte[] encode(SocketByteHashMap hashBody) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		SocketOutputStream buffer = new SocketOutputStream(out);
		
		String flag = hashBody.getString(Enum_Command_Header.Flag);
		if (flag == null)
			buffer.writeShort((short)0);
		else
			buffer.write(flag.getBytes());
		buffer.writeShort(hashBody.getShort(Enum_Command_Header.Cmd));
		buffer.writeShort(hashBody.getShort(Enum_Command_Header.Version));
		buffer.writeShort(hashBody.getShort(Enum_Command_Header.BodyLength));

		byte[] result = out.toByteArray();
		if(null == result){
			
		}
		
		buffer.close();
		buffer = null;
		out.close();
		out = null;
		
		return result;
	}
	
	/***********解包函数*****************
	 * ByteHashMap decode(byte[] buf)
	 * 入口参数：byte[] buf	//数据包
	 * 返回参数：ByteHashMap	//解析的结果集 
	 ***********************************/
	public static SocketByteHashMap decode(byte[] buf) throws IOException, EOFException {
		if (buf == null || buf.length < HEADER_SIZE)
			return null;	
		
		SocketByteHashMap result = new SocketByteHashMap();
		ByteArrayInputStream in = new ByteArrayInputStream(buf);
		SocketInputStream		buffer = new SocketInputStream(in);		
		
		result.putShort(Enum_Command_Header.Flag, buffer.readShort());
		result.putShort(Enum_Command_Header.Cmd, buffer.readShort());
		result.putShort(Enum_Command_Header.Version, buffer.readShort());
		result.putShort(Enum_Command_Header.BodyLength, buffer.readShort());
		
		return result;
	}
}
